using System;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib;
using System.IO;
using System.Reflection;

namespace UpdateCreator
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo AppDir = new DirectoryInfo(args[0]);
            string AppName = args[2];
            DirectoryInfo TargetDir = new DirectoryInfo(args[1]);
            if (!TargetDir.Exists)
                TargetDir.Create();
            FileInfo Executable = new FileInfo(Path.Combine(AppDir.FullName, AppName + ".exe"));
            if (!Executable.Exists)
                Console.WriteLine("ERROR: Application's .exe file not found in source dir!");
            Assembly asm = Assembly.LoadFrom(Executable.FullName);
            Version v = asm.GetName().Version;
            FileInfo UpdateFile = new FileInfo(Path.Combine(TargetDir.FullName, AppName + "-" + v.ToString() + ".zip"));

            Environment.SetEnvironmentVariable("VERSION", v.ToString(), EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("UPDATEFILENAME", UpdateFile.Name, EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("UPDATEFULLNAME", UpdateFile.FullName, EnvironmentVariableTarget.User);
            Environment.SetEnvironmentVariable("TARGETDIR", TargetDir.FullName, EnvironmentVariableTarget.User);

            Console.WriteLine("Source: " + AppDir.FullName);
            Console.WriteLine("Target: " + TargetDir.FullName);
            Console.WriteLine("Update file: " + Executable.Name);
            Console.WriteLine("-------------------------------------------------------");

            using (ZipFile zipfile = ZipFile.Create(UpdateFile.FullName))
            {
                zipfile.NameTransform = new ZipNameTransform(AppDir.FullName);
                zipfile.BeginUpdate();
                zipfile.Add(Executable.FullName);
                if (File.Exists(Executable.FullName + ".config"))
                    zipfile.Add(Executable.FullName + ".config");
                else
                    Console.WriteLine("WARNING: Application's .config file not found in source dir!");
                for (int i = 3; i < args.Length; i++)
                {
                    string[] files = Directory.GetFiles(AppDir.FullName, args[i]);
                    foreach (string f in files)
                    {
                        Console.WriteLine("Adding: " + f);
                        zipfile.Add(f);
                    }
                }
                zipfile.CommitUpdate();
            }
            //List<FileInfo> files = new List<FileInfo>();
            
            //Console.ReadKey();
        }

    }
}
